package cn.congine.wizarpos.mall.action;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.AddToShoppingCartInput;
import cn.congine.wizarpos.mall.model.open.AddToShoppingCartOutput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartItemNumInput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartItemNumOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/erp_product")
public class ErpProductAction {

	private static Logger logger = Logger.getLogger(ErpProductAction.class);

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	@RequestMapping(value = "/get")
	public ModelAndView getErpProduct(
			@RequestParam(value = "mid") String mid,//add xudongdong
			@RequestParam(value = "id") String id,
			HttpServletRequest httpRequest) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> erp = new HashMap<String, Object>();
		Map<String, Object> erpPro = new HashMap<String, Object>();

		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		
		//请求开放平台接口，获取商品信息
		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();		
		merchandiseSyncInput.setMid(mid);
		merchandiseSyncInput.setProductId(id);
		MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);		
		List<Merchandise> productList = merchandiseSyncOutput.getResult();		
		if (productList == null || productList.size() == 0) {
			data.put("err_message", "该商品不存在");
			return new ModelAndView("error", data);			
		}
		Merchandise product = productList.get(0);
		ErpProduct erpP = new ErpProduct();		
		try {
			BeanUtils.copyProperties(erpP, product);
		} catch (IllegalAccessException | InvocationTargetException e) {
			//do nothing
		}
		erpP.setId(product.getProductId());
		erpP.setStock(product.getStock());

		int total = 0;
		// carId为空（session过期，或者分享链接）购物车数量设置为0
		// 若是session过期后（非分享链接）导致cardId为空，则用户点击加入购物车或者是立即购买按钮后，将由加入购物车方法和立即购买方法对cardId判断，并跳转到登录页
		// cardId不空，请求开放平台获取购物车数量
		if (!StringUtils.isEmpty(cardId)) {
			GetShoppingCartItemNumInput input = new GetShoppingCartItemNumInput();
			input.setMid(mid);
			input.setCardId(cardId);
			GetShoppingCartItemNumOutput output = (GetShoppingCartItemNumOutput) wizarposOpenRestClient.post(input, "/wxshop/get_cart_item_num", GetShoppingCartItemNumOutput.class);		
			total = output.getNum();
		}
		erp.put(erpP.getId(), erpP.getPrice());
		if ("".equals(product.getPicUrl())) {
			erpP.setPicUrl(SysConstants.DEFAULT_PICTURE_DETAIL);
		} else {
			erpP.setPicUrl(Function.dealGridPicUrl(product.getPicUrl(), 700, 700));
		}		

		erpPro.put(erpP.getId(), product.getMemberPrice().toString());

		// 请求微信 js api的完整页面地址
		String baseUrl = getBaseURL(httpRequest);
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/erp_product/get");
		tmpUrl.append("?mid=");
		tmpUrl.append(mid);
		tmpUrl.append("&id=");
		tmpUrl.append(id);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));
		
		data.put("erpPro", erpPro);
		data.put("erp", erp);
		data.put("erpProduct", erpP);
		data.put("total", total);
		data.put("mid", mid);
		return new ModelAndView("product/detail", data);
	}	

	private String getBaseURL(HttpServletRequest httpRequest) {
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		return baseUrl;
	}
	
	/**
	 * 把商品加入到购物车
	 * 
	 * @param productId
	 * @param openId
	 * @param mid
	 * @param productPrice
	 * @return
	 */
	@RequestMapping(value = "/addToShoppingCart", method = RequestMethod.POST)
	@ResponseBody
	public RespMessage addToShoppingCart(
			@RequestParam(value = "productId") String productId,
			HttpServletRequest httpRequest) {
		RespMessage resp = new RespMessage();
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			resp.setCode(2);
			resp.setMessage("由于您长时间未操作，请重新登录");
			return resp;	
		}
		//请求开放平台接口，添加商品到购物车	
		AddToShoppingCartInput addToShoppingCartInput = new AddToShoppingCartInput();	
		addToShoppingCartInput.setCardId(cardId);
		addToShoppingCartInput.setProductId(productId);
		AddToShoppingCartOutput output = (AddToShoppingCartOutput) wizarposOpenRestClient.post(addToShoppingCartInput, "/wxshop/addToShoppingCart", AddToShoppingCartOutput.class);
		
		if ("0".equals(output.getCode())) {
			resp.setCode(0);
			resp.setMessage("添加商品成功！");
			return resp;			
		} else if ("60022".equals(output.getCode())) { //非法商品编号:
			resp.setCode(1);
			resp.setMessage("该商品已下架");
			return resp;		
		} else if ("60001".equals(output.getCode())) {//非法慧商户号
			resp.setCode(1);
			resp.setMessage("该商户不存在");
			return resp;			
		} else if ("60058".equals(output.getCode())) {//商品未设置价格
			resp.setCode(1);
			resp.setMessage("保存商品失败！");
			return resp;			
		} else if ("60019".equals(output.getCode())) {//非微信会员，无会员卡，前往会员卡领取页面
			resp.setCode(3);
			resp.setMessage("请先领取会员卡，再购买商品！");
			return resp;			
		} else {
			resp.setCode(1);
			resp.setMessage("保存商品失败！");
			return resp;			
		}		
	}
}
